package com.ruicar.afs.cloud.apply.pre.approve.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.apply.common.entity.PreApproveInfo;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.contract.enums.CertTypePictureEnum;
import com.ruicar.afs.cloud.apply.contract.enums.UploadIDImageSceneEnum;
import com.ruicar.afs.cloud.apply.contract.service.CreatContractService;
import com.ruicar.afs.cloud.apply.pre.approve.condition.PreApproveCondition;
import com.ruicar.afs.cloud.apply.pre.approve.mapper.PreApproveMapper;
import com.ruicar.afs.cloud.apply.pre.approve.service.PreApproveService;
import com.ruicar.afs.cloud.apply.pre.approve.service.impl.PreApproveServiceImpl;
import com.ruicar.afs.cloud.apply.pre.loan.mapper.ApplyOrderInfoMapper;
import com.ruicar.afs.cloud.apply.pre.smallprogram.condition.TencentCloudNuclearBodyCondition;
import com.ruicar.afs.cloud.bizcommon.print.enums.ServiceClientTypeEnum;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.common.core.query.QueryCondition;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.ParseException;
import java.util.*;

/**
 * @ClassName:PreApproveController
 * @Description: 预审批-controller
 * @Author:jihuigeng
 * @Date:2020/5/9 19:06
 * @Version: V1.0
 **/
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/preApprove")
@ApiOperation("预审批信息管理")
public class PreApproveController {
    private final PreApproveService preApproveService;
    private final PreApproveMapper preApproveMapper;
    private final CreatContractService creatContractService;
    private final PreApproveServiceImpl preApproveServiceImpl;
    private final ApplyOrderInfoMapper orderInfoMapper;

    /**
     * 预审批信息新增提交/
     * 已提交数据更新/
     * 暂存数据更新
     * 并生成二维码
     *
     * @param condition
     * @return
     * @throws ParseException
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/save")
    @ApiOperation(value = "保存/更新已提交数据/更新暂存数据")
    public IResponse save(@Valid @RequestBody PreApproveCondition condition) {
        Map save = preApproveService.savePreInfo(condition);
        log.info("二维码信息:{}", save);
        //上传附件
        if (condition.getPcOrApp().equals(ApplyConstants.PC_UPLOAD)) {
            if (condition.getContractFileVos() != null) {
                preApproveService.queryAndRemove(save.get("id").toString(), CertTypePictureEnum.PRE_BORROWER_ID_CARD_FRONT.getIndex());
                preApproveService.queryAndRemove(save.get("id").toString(), CertTypePictureEnum.PRE_BORROWER_ID_CARD_BACK.getIndex());
                preApproveServiceImpl.saveOrUpdateFile(condition.getContractFileVos(), save.get("id").toString());
            }
        } else if (condition.getPcOrApp().equals(ApplyConstants.APP_UPLOAD)) {
            this.preApproveService.storeCardImage(condition.getFrontIDCard(), condition.getReverseIDCard(), UploadIDImageSceneEnum.PRE_APPROVE_SCENE.getCode(), null, String.valueOf(save.get("id")));
        }
        //预审批，批量模板生成
        creatContractService.preAuthorBatchPrint(condition.getBusinessType(), (Long) save.get("id"), AfsEnumUtil.key(ServiceClientTypeEnum.APP));
        return IResponse.success(save);
    }


    /**
     * 暂存
     *
     * @param condition
     * @return
     * @throws ParseException
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/store")
    @ApiOperation(value = "暂存")
    public IResponse store(@Valid @RequestBody PreApproveCondition condition) throws ParseException {
        if (StringUtil.isEmpty(condition.getIsLongTerm())) {
            if (condition.getCertEndDate() == null) {
                return IResponse.fail("证件结束日期不能为空");
            } else if (DateUtil.format(condition.getCertEndDate(), "yyyy-MM-dd").compareTo(DateUtil.format(new Date(), "yyyy-MM-dd")) < 0) {
                //验证证件有效期
                return IResponse.fail("证件已过有效期");
            }
        }
        //根据身份证号，业务类型,部门id查询信息
        PreApproveCondition preApproveCondition = new PreApproveCondition();
        preApproveCondition.setCertNo(condition.getCertNo());
        preApproveCondition.setBusinessType(condition.getBusinessType());
        preApproveCondition.setCreateBy(SecurityUtils.getUsername());
        JSONArray jsonArray = SecurityUtils.getUser().getUserExtInfo().getJSONArray(ApplyConstants.DEPT_IDS);
        if (jsonArray != null) {
            preApproveCondition.setDeptIds(jsonArray.toJavaList(String.class));
        }
        List<PreApproveInfo> preApproveInfoList = this.preApproveMapper.getPreApproveInfo(preApproveCondition);
        if (CollectionUtil.isNotEmpty(preApproveInfoList)) {
            for (PreApproveInfo preApproveInfo : preApproveInfoList) {
                if ((ApplyConstants.PRE_APPROVE_REFUSE.equals(preApproveInfo.getApplyStatus())
                        || preApproveInfo.getApplyStatus().equals(ApplyConstants.PRE_APPROVE_INVALID))) {
                    condition.setCreateBy(SecurityUtils.getUsername());
                    condition.setCreateTime(new Date());
                    condition.setDeptId(String.valueOf(SecurityUtils.getUser().getDeptId()));
                    condition.setSellerRealName(SecurityUtils.getUser().getUserRealName());
                    //渠道id
                    condition.setChannelId(SecurityUtils.getUser().getUserExtInfo().getLong("channelId"));
                    condition.setChannelName(SecurityUtils.getUser().getUserExtInfo().getJSONObject("channelInfo").get("channelFullName").toString());
                    condition.setApplyStatus(ApplyConstants.PRE_APPROVE_PRE_SUBMIT);
                    this.preApproveService.save(condition);
                    //上传证件照
                    if (condition.getPcOrApp().equals(ApplyConstants.PC_UPLOAD)) {
                        if (condition.getContractFileVos() != null) {
                            preApproveService.queryAndRemove(condition.getId().toString(), CertTypePictureEnum.PRE_BORROWER_ID_CARD_FRONT.getIndex());
                            preApproveService.queryAndRemove(condition.getId().toString(), CertTypePictureEnum.PRE_BORROWER_ID_CARD_BACK.getIndex());
                            preApproveServiceImpl.saveOrUpdateFile(condition.getContractFileVos(), condition.getId().toString());
                        }
                    } else if (condition.getPcOrApp().equals(ApplyConstants.APP_UPLOAD)) {
                        this.preApproveService.storeCardImage(condition.getFrontIDCard(), condition.getReverseIDCard(), UploadIDImageSceneEnum.PRE_APPROVE_SCENE.getCode(), null, String.valueOf(condition.getId()));
                    }
                    return IResponse.success("保存成功");
                } else if (ObjectUtil.isNotNull(preApproveInfo) || preApproveInfo.getApplyDate() != null) {
                    //并且证件号码相同，又办理过相同业务，那么就不录入，返回错误信息
                    if (preApproveInfo.getCertNo().equals(condition.getCertNo()) &&
                            preApproveInfo.getBusinessType().equals(condition.getBusinessType())) {
                        return IResponse.fail("您已办理过当前业务");
                    }
                }
            }
        } else {
            //创建人
            condition.setCreateBy(SecurityUtils.getUsername());
            //创建时间
            condition.setCreateTime(new Date());
            //部门id
            condition.setDeptId(SecurityUtils.getUser().getDeptId().toString());
            condition.setSellerRealName(SecurityUtils.getUser().getUserRealName());
            //渠道id
            condition.setChannelId(SecurityUtils.getUser().getUserExtInfo().getLong("channelId"));
            condition.setChannelName(SecurityUtils.getUser().getUserExtInfo().getJSONObject("channelInfo").get("channelFullName").toString());
            //暂存更新状态为:待提交
            condition.setApplyStatus(ApplyConstants.PRE_APPROVE_PRE_SUBMIT);
            this.preApproveService.save(condition);
            PreApproveInfo approveInfo = this.preApproveService.getOne(Wrappers.<PreApproveInfo>query().lambda()
                    .eq(StringUtil.isNotEmpty(condition.getCertNo()), PreApproveInfo::getCertNo, condition.getCertNo())
                    .eq(StringUtil.isNotEmpty(condition.getBusinessType()), PreApproveInfo::getBusinessType, condition.getBusinessType())
                    .eq(StringUtil.isNotEmpty(SecurityUtils.getUsername()), PreApproveInfo::getCreateBy, SecurityUtils.getUsername()));
            //上传证件照
            if (condition.getPcOrApp().equals(ApplyConstants.PC_UPLOAD)) {
                if (condition.getContractFileVos() != null) {
                    preApproveService.queryAndRemove(condition.getId().toString(), CertTypePictureEnum.PRE_BORROWER_ID_CARD_FRONT.getIndex());
                    preApproveService.queryAndRemove(condition.getId().toString(), CertTypePictureEnum.PRE_BORROWER_ID_CARD_BACK.getIndex());
                    preApproveServiceImpl.saveOrUpdateFile(condition.getContractFileVos(), condition.getId().toString());
                }
            } else if (condition.getPcOrApp().equals(ApplyConstants.APP_UPLOAD)) {
                this.preApproveService.storeCardImage(condition.getFrontIDCard(), condition.getReverseIDCard(), UploadIDImageSceneEnum.PRE_APPROVE_SCENE.getCode(), null, String.valueOf(condition.getId()));
            }
            return IResponse.success(approveInfo.getId());
        }
        return null;
    }

    /**
     * 二维码刷新
     *
     * @return
     */
    @PostMapping("/refresh")
    @ApiOperation(value = "刷新二维码")
    public IResponse refresh(@Valid @RequestBody PreApproveCondition condition) {
        TencentCloudNuclearBodyCondition bodyCondition = new TencentCloudNuclearBodyCondition();
        if (ApplyConstants.PRINCIPAL_BORROWER.equals(condition.getCustRole())) {
            bodyCondition.setSignScene(ApplyConstants.PRINCIPAL_BORROWER);
            bodyCondition.setCustId(condition.getId());
        } else if (ApplyConstants.COMMON_BORROWER.equals(condition.getCustRole())) {
            bodyCondition.setSignScene(ApplyConstants.COMMON_BORROWER);
            bodyCondition.setCustId(condition.getId());
        } else if (ApplyConstants.GUARANTOR.equals(condition.getCustRole())) {
            bodyCondition.setSignScene(ApplyConstants.GUARANTOR);
            bodyCondition.setCustId(condition.getId());
        } else {
            bodyCondition.setSignScene(ApplyConstants.MESSAGE_TYPE_ZERO);
            bodyCondition.setPreId(condition.getId());
        }
        Map qrCode = this.preApproveService.getSmallProgramQrCode(bodyCondition);
        return IResponse.success(qrCode);
    }

    /**
     * 通过id删除预审批系统
     *
     * @param condition
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    @ApiOperation(value = "删除")
    @Transactional(rollbackFor = Exception.class)
    @SysLog("删除预审批信息")
    public IResponse<Boolean> delete(@Valid @RequestBody PreApproveCondition condition) {
        preApproveService.removeById(condition.getId());
        return new IResponse<Boolean>().setMsg("删除数据成功");
    }


    /**
     * 修改删除标识
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "修改删除标识")
    @Transactional(rollbackFor = Exception.class)
    @SysLog("修改删除标识")
    public IResponse<Boolean> updateDelFlag(@PathVariable Long id) {
        boolean b = preApproveService.removeById(id);
        return new IResponse<Boolean>().setMsg("修改删除标识成功");
    }


    /**
     * 修改预审批信息
     *
     * @param condition
     * @return
     * @throws ParseException
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/edit")
    @ApiOperation(value = "修改数据")
    public IResponse edit(@Valid @RequestBody PreApproveCondition condition) throws ParseException {
        Map map = preApproveService.editPreInfo(condition);
        //预审批，批量模板生成
        creatContractService.preAuthorBatchPrint(condition.getBusinessType(), condition.getId(), AfsEnumUtil.key(ServiceClientTypeEnum.APP));
        return IResponse.success(map);
    }

    /**
     * 根据多条件，分页获取预申请信息
     *
     * @param condition
     * @return
     */
    @PostMapping("/getByCondition")
    @ApiOperation("多条件分页,分权限,获取预申请信息")
    public IResponse<IPage<PreApproveInfo>> getByCondition
    (@RequestBody QueryCondition<PreApproveCondition> condition) {
        Page page = new Page(condition.getPageNumber(), condition.getPageSize());
        IPage data = new Page();
        String startDate = condition.getCondition().getStartDate();
        String endDate = condition.getCondition().getEndDate();

        // 声明一个状态的集合
        List<String> allStatus = new ArrayList<>();
        if (condition.getCondition().getAllStatus() != null && condition.getCondition().getAllStatus() != "") {
            String[] ids = condition.getCondition().getAllStatus().split(",");
            if (ids.length > 0) {
                for (int j = 0; j < Arrays.asList(ids).size(); j++) {
                    allStatus.add(Arrays.asList(ids).get(j));
                }
            } else {
                allStatus = null;
            }
        } else {
            allStatus = null;
        }
        if (StringUtil.isNotEmpty(startDate) && startDate.equals(endDate)) {
            condition.getCondition().setStartDate(startDate + " 00:00:00");
            condition.getCondition().setEndDate(endDate + " 23:59:59");
        } else if (StringUtil.isNotEmpty(startDate) && StringUtil.isNotEmpty(endDate)) {
            condition.getCondition().setStartDate(startDate + " 00:00:00");
            condition.getCondition().setEndDate(endDate + " 23:59:59");
        }
        condition.getCondition().setCreateBy(SecurityUtils.getUsername());
        JSONArray jsonArray = SecurityUtils.getUser().getUserExtInfo().getJSONArray(ApplyConstants.DEPT_IDS);
        if (jsonArray != null) {
            condition.getCondition().setDeptIds(jsonArray.toJavaList(String.class));
        }
        List list = new ArrayList();
        IPage<PreApproveInfo> infoList = this.preApproveMapper.getPreApproveInfoList(condition.getCondition(), page, allStatus);
        infoList.getRecords().stream().forEach(preApproveInfo -> {
            Map<String, String> fileId = this.preApproveService.getFileId(String.valueOf(preApproveInfo.getId()), null);
            preApproveInfo.setIdData(fileId);
            //获取征信授权书
            List<ComAttachmentFile> idCardImage = orderInfoMapper.getIdCardImage(String.valueOf(preApproveInfo.getId()), "creditAuthorizationFile", "orderApply");
            if (CollectionUtil.isNotEmpty(idCardImage)) {
                idCardImage.forEach(comAttachmentFile -> {
                    if (ObjectUtil.isNotNull(comAttachmentFile)) {
                        preApproveInfo.setFileServiceOne(comAttachmentFile);
                    }
                });
            }
            list.add(preApproveInfo);
        });
        data.setRecords(list);
        data.setTotal(infoList.getTotal());
        data.setPages(infoList.getPages());
        data.setSize(infoList.getSize());
        data.setCurrent(infoList.getCurrent());
        return IResponse.success(data);
    }


    /**
     * App用微信二维码
     *
     * @return
     */
    @PostMapping("/getWeChatCode")
    @ApiOperation("App用微信二维码")
    public IResponse getWeChatCode() {
        Map qrCode = this.preApproveService.getQrCode();
        return IResponse.success(qrCode);
    }

    /**
     * 通过申请编号、客户信息、证件号码查询预审批信息
     *
     * @param condition
     * @return
     */
    @PostMapping("/getPreApproveInfo")
    @ApiOperation("通过申请编号、客户信息、证件号码查询预审批信息")
    public IResponse getPreApproveInfo(@RequestBody PreApproveCondition condition) {

        PreApproveInfo preApproveInfo = preApproveService.getPreApproveInfo(condition);
        return IResponse.success(preApproveInfo);
    }

    /**
     * 更新人脸识别、三要素、签约结果
     *
     * @param condition
     * @return
     */
    @PostMapping("updatePreApproveInfo")
    @ApiOperation("更新人脸识别、三要素、签约结果")
    public IResponse updatePreApproveInfo(@RequestBody PreApproveCondition condition) {

        PreApproveInfo preApproveInfo = preApproveService.updatePreApproveInfo(condition);
        return IResponse.success(Boolean.TRUE);
    }
}